package com.xsoft.demo10;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.xsoft.demo10.fragment.GoodsListFragment;
import com.xsoft.demo10.fragment.MineFragment;
import com.xsoft.demo10.fragment.ShopsListFragment;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout home;
    private LinearLayout shop;
    private LinearLayout my;
    private Fragment homeFragment;
    private Fragment shopFragment;
    private Fragment myFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        home = (LinearLayout) findViewById(R.id.home);
        home.setOnClickListener(this);
        shop = (LinearLayout) findViewById(R.id.shop);
        shop.setOnClickListener(this);
        my = (LinearLayout) findViewById(R.id.my);
        my.setOnClickListener(this);
        onClick(home);
    }

    @Override
    public void onClick(View v) {
        //获取Fragment管理器
        FragmentManager fragmentManager = getSupportFragmentManager();
        //开启事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (v.getId()) {
            case R.id.home:
                home.setSelected(true);
                shop.setSelected(false);
                my.setSelected(false);
                if (homeFragment == null) {
                    homeFragment = new GoodsListFragment();
                    transaction.add(R.id.container, homeFragment);
                } else {
                    transaction.show(homeFragment);
                }
                break;
            case R.id.shop:
                home.setSelected(false);
                shop.setSelected(true);
                my.setSelected(false);
                if (shopFragment == null) {
                    shopFragment = new ShopsListFragment();
                    transaction.add(R.id.container, shopFragment);
                } else {
                    transaction.show(shopFragment);
                }
                break;
            case R.id.my:
                home.setSelected(false);
                shop.setSelected(false);
                my.setSelected(true);
                if (myFragment == null) {
                    myFragment = new MineFragment();
                    transaction.add(R.id.container, myFragment);
                } else {
                    transaction.show(myFragment);
                }
                break;
        }
        //提交事务
        transaction.commitAllowingStateLoss();
    }
}